package utm.servlet.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import md.utm.simple_jdbc.MySQLAccess;
import md.utm.simple_jdbc.Person;

// Extend HttpServlet class
public class ReadPersonsFromDatabase extends HttpServlet {

	private String message;

	@Override
	public void init() throws ServletException {
		// Do required initialization
		message = "Persons";
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		MySQLAccess access = new MySQLAccess();
		List<Person> persons = access.readFromDataBase();
		// Set response content type
		response.setContentType("text/html");

		// Actual logic goes here.
		PrintWriter out = response.getWriter();
		out.println("<h1>" + message + "</h1>");
		out.println("<br/>");
		out.print("<table>");
		out.print("<thead>");
		out.print("<tr>");
		out.print("<td>");
		out.print("Name");
		out.print("</td>");
		out.print("<td>");
		out.print("Surname");
		out.print("</td>");
		out.print("<td>");
		out.print("Year of birth");
		out.print("</td>");
		out.print("<td>");
		out.print("Is student");
		out.print("</td>");
		out.print("</tr>");
		out.print("</thead>");
		for (Person person : persons) {
			out.print("<tr>");
			out.print("<td>");
			out.print(person.getName());
			out.print("</td>");
			out.print("<td>");
			out.print(person.getSurname());
			out.print("</td>");
			out.print("<td>");
			out.print(person.getYearOfBirth());
			out.print("</td>");
			out.print("<td>");
			out.print(person.isStudent());
			out.print("</td>");
			out.print("</tr>");
		}
		out.print("</table>");
		access.readFromDataBase();
	}

	@Override
	public void destroy() {
		// do nothing.
	}
}